package logic.pay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

/**
 * 支付帮助类
 * @author 刘宾  
 * @date 2015年4月13日 下午4:20:24
 */
public class PayUtil{

	//商户PID
	public static final String PARTNER = "2088811379296062";
	//商户收款账号
	public static final String SELLER = "cw@shwread.cn";
	//商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMFBImTkAdY3SP+jsHkGbleELC/GY6P4N0h+NnKF5AMPVFvYvnVRkJT08tZ0YSEJ35O9apoS+rStaAAs3P5X2TNW65LefWiar456drAY14n6WsZUk0VPUduoVAgxsZEoBHq6dP5qR/0uVpcMVmURTOoSmDdWrE+zpns8m1bq6ZaVAgMBAAECgYAmyc3/dgwwVNRgCxjGkdXf1vWPeUBSjuV5tWt0PQ9w1cjWzoAbyA0++JMtHBrKqNKpMqGM3zZWwV9Yeai5nCRJ4lx3SNcz241HkCoOwhZany/TcsUu1dXEHCJoklwcPAPnqT6QlRwc1Ai5+xe1U0yxcOk+Wc3xt9kvx3jmVfUYWQJBAORyH0Uwz08X9PX0XKojP7+6yqnijaRwL8BJ1Dof4VUbMfkU7ULYHk86BCN08iGsmGVdtvWFu9dCrWmXyCaJDi8CQQDYkGJoesmVrjFKjzEPZdhi+tttLclRqDix2SVHJ4fiyhLm2q3xv3hsBf94ja1rIVYLNysd2J+AyQMs8/P9kRp7AkAViPSNrzY7vIRpEyoRF9WQm2kzbpnvoGu/8rXA7PRu82tYkbJ0FK92xH9TYFja98w98gGnT34Posd6JsbFazIdAkBgUk/CwqI4deKsk+WxQI4u7/56n/vD2vtkdv1ymW2B/HjNvwPQ22WXPk+zcehpFsmrcV03CCthX4aPDu49oLVTAkEAoXED86o/8fKCVJMnBEhyRdKs8R1BD/M2FoqZ+4Pjm0iny1hKW56w1e1wHX367S7k5/iT19K7VqJsWVN0ItMyvQ==";
	//支付宝公钥
	public static final String RSA_PUBLIC = "";
	
	//TODO 服务器异步通知页面路径(商测)
//	private static final String ASYNC_NOTIFICATION_SERVER_PAGE = "http://121.41.18.34:555/hzlqswserver/receiveNotify.do";
	//TODO 服务器异步通知页面路径(商用)
	private static final String ASYNC_NOTIFICATION_SERVER_PAGE = "http://42.121.255.69:8080/hzlqswserver/receiveNotify.do";


	public static final int    SDK_PAY_FLAG           = 1;
	public static final int    SDK_CHECK_FLAG         = 2;
	public static final int    SDK_CHECK_ACCOUNT_FLAG = 3;


	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public static void pay(final Activity activity,final Handler mHandler,String orderInfo) {
		// 订单
//		String orderInfo = getOrderInfo("测试的商品", "该测试商品的详细描述", "0.01");

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(activity);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public static void check(final Activity activity,final Handler mHandler) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(activity);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public static void getSDKVersion(final Activity activity,final Handler mHandler) {
		PayTask payTask = new PayTask(activity);
		String version = payTask.getVersion();
		Toast.makeText(activity, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 创建订单信息
	 * @param outTradeNo 商户网站唯一订单号
	 * @param subject 商品名称
	 * @param body 商品详情
	 * @param price 商品金额
	 * @return
	 */
	public static String getOrderInfo(String outTradeNo,String subject, String body, String price) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + outTradeNo + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		//服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + ASYNC_NOTIFICATION_SERVER_PAGE + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public static String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public static String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
